package com.tanhua.server.service;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.db.*;
import com.tanhua.model.db.*;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserInfoVoAge;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SettingService {

    @DubboReference
    private SettingApi settingApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询用户通用设置
     * @return
     */
    public SettingsVo querySettings() {
        // 获得登录用户的信息
        User user = UserHolder.getUser();

        // 通过用户的id查询通用设置信息
        Settings settings = settingApi.findUserById(user.getId());

        // 通过用户的id查询问题列表信息
        Question question = questionApi.findUserById(user.getId());

        // 构造需要返回的vo对象，传输数据
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setPhone(user.getMobile());
        settingsVo.setStrangerQuestion(question != null ? question.getTxt() : "妹妹你来了呀！");

        if(settings != null){
            BeanUtils.copyProperties(settings,settingsVo);
        }

        // 返回
        return settingsVo;
    }

    /**
     * 设置陌生人问题
     * @return
     */
    public void saveQuestions(Map<String, String> params) {
        Question question = new Question();
        // 设置的问题
        String content = params.get("content");
        Long userId = UserHolder.getUserId();
        question.setUserId(userId);
        question.setTxt(content);
        questionApi.save(question);
    }


    /**
     * 通知设置 - 保存
     * @return
     */
    public void saveSettings(SettingsVo settingsVo) {

        Settings settings = new Settings();
        BeanUtils.copyProperties(settingsVo,settings);

        Long userId = UserHolder.getUserId();
        settings.setUserId(userId);

        settingApi.save(settings);
    }

    /**
     * 黑名单 - 翻页列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult<UserInfoVoAge> blacklistPage(Long page, Long pagesize) {
        // 获取当前用户id
        Long userId = UserHolder.getUserId();

        // 调用服务分页查询黑名单列表数据
        PageResult<BlackList> blackListpageResult = blackListApi.blackListPage(page,pagesize,userId);

        if(blackListpageResult == null || CollectionUtils.isEmpty(blackListpageResult.getItems())){
            return new PageResult<>(0l,10l,0l,1l,null);
        }

        // 拿到黑名单列表
        List<BlackList> blackLists = blackListpageResult.getItems();

        // 定义List<Long> 接收黑名单ids
        List<Long> blackListIds = new ArrayList<>();

        // 循环遍历黑名单列表获取出黑名单用户ids
        for (BlackList blackList : blackLists) {
            blackListIds.add(blackList.getBlackUserId());
        }


        // 根据黑名单用户ids调用服务查询黑名单用户集合数据
        List<UserInfo> userInfoList = userInfoApi.findByBatchIds(blackListIds);

        List<UserInfoVoAge> userInfoVoAgeList = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            UserInfoVoAge userInfoVoAge = new UserInfoVoAge();
            BeanUtils.copyProperties(userInfo,userInfoVoAge);
            userInfoVoAgeList.add(userInfoVoAge);
        }

        // 构造PageResult对象返回
        PageResult<UserInfoVoAge> infoVoAgePageResult = new PageResult<>();
        BeanUtils.copyProperties(blackListpageResult,infoVoAgePageResult);
        infoVoAgePageResult.setItems(userInfoVoAgeList);


        return infoVoAgePageResult;
    }

    /**
     * 黑名单 - 移除
     * @param uid
     */
    public void removeBlackList(Long uid) {

        Long loginUserId = UserHolder.getUserId();
        blackListApi.removeBlackList(uid,loginUserId);
    }

    /**
     * 修改手机号- 1 发送短信验证码
     * @return
     */
    public void sendVerificationCode() {
        User user = UserHolder.getUser();
        String mobile = user.getMobile();
        String code = "123456";
        smsTemplate.sendSms(mobile,code);

        // 将验证码存入redis中5分钟有效
        String key = "VALIDATE_CODE_" + mobile;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
    }

    /**
     * 修改手机号 - 2 校验验证码
     */
    public Map<String,Boolean> checkVerificationCode(Map<String,String> params) {
        boolean flag = false;
        Map<String,Boolean> map = new HashMap<>();
        String verificationCode = params.get("verificationCode");

        User user = UserHolder.getUser();
        String mobile = user.getMobile();
        String key = "VALIDATE_CODE_" + mobile;
        String reidsCode = (String) redisTemplate.opsForValue().get(key);


        if(verificationCode.equals(reidsCode)){
            flag = true;
            map.put("verification",flag);
            return map;
        }
        map.put("verification",flag);
        return map;
    }

    /**
     * 修改手机号 - 3 保存
     */
    public void updatePhone(@RequestBody Map<String,String> params) {
        // 拿到用户要修改的电话
        User user = new User();
        Long userId = UserHolder.getUserId();
        String phone = params.get("phone");
        user.setId(userId);
        user.setMobile(phone);
        userApi.updatePhone(user);
    }
}
